import { MessageEvent, ServerMessageEmit } from '@/shared/message'

const serverMessage = new ServerMessageEmit(true)

function dispatchInject(tabId?: number) {
  chrome.action.setBadgeText({ tabId, text: 'ON' })
  chrome.action.setBadgeBackgroundColor({ tabId, color: 'green' })
  chrome.action.setBadgeTextColor({ tabId, color: '#fff' })
  serverMessage.dispatch(new MessageEvent('inject'), tabId)
}

const MENU_ID = 'inject'

chrome.contextMenus.create({
  id: MENU_ID,
  title: '颜色管理器'
})

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === MENU_ID && tab) {
    dispatchInject(tab.id)
  }
})

chrome.action.onClicked.addListener((tab) => {
  if (tab.id && tab.url?.startsWith('http')) {
    dispatchInject(tab.id)
  }
})
